<template>
  <el-dialog
    ref="selectUserPermission"
    title="用户管理"
    width="400px"
    :close-on-click-modal="false"
    :visible.sync="params.visible"
  >
    <compTree
      ref="tree"
      :show-search="false"
      :tree-show-checkbox="true"
      :comp-tree-height="350"
      :tree-default-checked-keys="treeDefaultCheckedKeys"
      :tree-default-expanded-keys="treeDefaultExpandedKeys"
      :tree-data="treeData"
    />
    <dialog-btn slot="footer">
      <el-checkbox
        v-show="showAdmin"
        v-model="isAdmin"
        style="float: left"
      >系统管理员权限</el-checkbox>
    </dialog-btn>
  </el-dialog>
</template>

<script>
import { ParamArr, SQLTable } from '../../../public/js/paramarr'
import Global from '../../../public/js/global'
import { getRoleUserMgr, setRoleUserMgr } from '@/api/user'
export default {
  name: 'SelectUserPermission',
  components: { DialogBtn: () => import('@/components/Dialog/DialogBtn.vue') },
  props: {
    params: {
      type: Object,
      default() {
        return {
          visible: false, // 弹窗是否可见
          id: '', // 角色id
          pid: '' // 角色pid
        }
      }
    }
  },
  data() {
    return {
      treeData: [],
      treeDefaultCheckedKeys: [],
      treeDefaultExpandedKeys: [],
      showAdmin: true,
      isAdmin: false,
      roleUserTable: {},
      qryUserTable: {}
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.$showLoading(
        '正在加载',
        this.$refs.selectUserPermission.$el.querySelector('div')
      )
      const vPar = new ParamArr()
      vPar.setStr('RoleID', this.params.id)
      vPar.setStr('RoleIDs', this.params.pid)
      getRoleUserMgr(vPar)
        .then((vPar) => {
          const table = new SQLTable(vPar.getTable('QryGroup'))
          const roleUserTable = new SQLTable(vPar.getTable('k_role_user'))
          this.roleUserTable = roleUserTable
          const roleUser = new SQLTable(vPar.getTable('k_role_user_mgr'))
          const nodeMap = new Map()
          const nodes = []
          table.first()
          while (!table.eof()) {
            const node = {}
            const pnode = Global.getTreeviewPNode(
              nodeMap,
              nodes,
              table.getValueByName('PID')
            )
            node['id'] = table.getValueByName('ID')
            node['pid'] = table.getValueByName('PID')
            node['name'] = table.getValueByName('Name')
            node['text'] = node.name
            node['icon'] = 'wenjianyi'
            node['folder'] = true
            if (roleUser.locate('ID', [node.id])) {
              this.treeDefaultCheckedKeys.push(node.id)
            }
            pnode.push(node)
            nodeMap.set(node.id, node)
            table.next()
          }
          const qryUserTable = new SQLTable(vPar.getTable('QryUser'))
          this.qryUserTable = qryUserTable
          qryUserTable.first()
          while (!qryUserTable.eof()) {
            const node = {}
            const pnode = Global.getTreeviewPNode(
              nodeMap,
              nodes,
              qryUserTable.getValueByName('PID')
            )
            if (qryUserTable.getIntByName('Enabled') === 1) {
              node['id'] = qryUserTable.getValueByName('ID')
              node['pid'] = qryUserTable.getValueByName('PID')
              node['name'] = qryUserTable.getValueByName('UserName')
              node['userId'] = qryUserTable.getValueByName('UserID')
              node['text'] = node.name
              node['icon'] = 'yonghu'
              node['folder'] = false
              if (roleUser.locate('ID', [node.id])) {
                this.treeDefaultCheckedKeys.push(node.id)
              }
              pnode.push(node)
              nodeMap.set(node.id, node)
            }
            qryUserTable.next()
          }
          // 移除空目录
          nodeMap.forEach(function(node) {
            if (node.folder && node.pid && !node.nodes) {
              const pNode = nodeMap.get(node.pid)
              const cNodes = pNode.nodes
              cNodes.splice(cNodes.indexOf(node), 1)
            }
          })
          // 移除空根目录
          for (let i = 0; i < nodes.length; i++) {
            const node = nodes[i]
            if (!node.nodes || node.nodes.length === 0) {
              nodes.splice(nodes.indexOf(node), 1)
            }
          }
          this.treeData = nodes
          this.isAdmin = roleUser.locate('ID', ['0'])
          this.showAdmin = vPar.getBool('PAdmin') && nodes.length !== 0
        })
        .finally(() => {
          this.$closeLoading()
        })
    },
    confirm() {
      const vPar = new ParamArr()
      const nodes = this.$refs.tree.getCheckedNodes()
      const idList = []
      let j = 0
      for (let i = 0; i < nodes.length; i++) {
        if (!nodes[i].folder) {
          vPar.setStr(`ID_${j}`, nodes[i].id)
          vPar.setStr(`Name_${j}`, nodes[i].name)
          idList.push(nodes[i].id)
          j++
        }
      }
      vPar.setInt('Count', j)
      vPar.setStr('RoleID', this.params.id)
      const tips = []
      this.roleUserTable.first()
      while (!this.roleUserTable.eof()) {
        if (
          idList.indexOf(this.roleUserTable.getValueByName('LoginID')) === -1
        ) {
          this.qryUserTable.first()
          while (!this.qryUserTable.eof()) {
            if (
              this.roleUserTable.getValueByName('LoginID') ===
              this.qryUserTable.getValueByName('ID')
            ) {
              tips.push(this.qryUserTable.getValueByName('UserName'))
            }
            this.qryUserTable.next()
          }
        }
        this.roleUserTable.next()
      }
      if (tips.length !== 0) {
        return this.$message.warning(
          '用户' + tips + '在人员关系中已勾选，请先取消'
        )
      }
      vPar.setBool('IsAdmin', this.isAdmin)
      setRoleUserMgr(vPar).then(() => {
        if (this.params.confirm !== undefined) {
          this.params.confirm()
        } else {
          this.$emit('confirm', '')
        }
      })
    },
    cancel() {
      this.params.visible = false
    }
  }
}
</script>

<style scoped>
</style>
